package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/subsets/">子集2</a>
 */
public class SubSetsII {
    public static void main(String[] args) {
        SubSetsII subSets2 = new SubSetsII();
        List<List<Integer>> subsets = subSets2.subsetsWithDup(new int[]{1, 2, 2});
        subsets.forEach(System.out::println);
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        backTracing(nums, new int[nums.length], 0, new ArrayList<>(), res);
        return res;
    }

    public void backTracing(int[] nums, int[] used, int idx, List<Integer> list, List<List<Integer>> res) {
        if (idx > nums.length) {
            return;
        }

        res.add(new ArrayList<>(list));

        for (int i = idx; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0) {
                continue;
            }
            list.add(nums[i]);
            used[i] = 1;
            backTracing(nums, used, i + 1, list, res);
            list.remove(list.size() - 1);
            used[i] = 0;
        }
    }
}
